package gugga.eventHelpers
{
	import flash.events.IEventDispatcher;
	import flash.events.Event;
	
	/**
	 * <code>EventRethrower</code> provide us with a simple mechanism 
	 * to intercept a certain event and to rethrow it, thus dispatching 
	 * the same event with a different source for it (the 
	 * <code>target</code>-property of the event will be the specified 
	 * context passed as an argument to the 
	 * <code>EventRethrower</code>-constructor). 
	 * <p>
	 * The correct use of the <code>EventRethrower</code> is throught 
	 * its static <code>create()</code> and 
	 * <code>createSingleTimeRethrower()</code> methods.
	 */
	public class EventRethrower
	{
		private var mContext : IEventDispatcher;
		private var mDispatcher : IEventDispatcher;
		private var mEvent : String;
		private var mRethrowOnce : Boolean;
		
		public function get Event() : String
		{
			return mEvent;
		}
		
		public function EventRethrower(aContext : IEventDispatcher, 
			aDispatcher : IEventDispatcher, aEvent : String, aRethrowOnce : Boolean = false)
		{
			mContext = aContext;
			mDispatcher = aDispatcher;
			mEvent = aEvent;
			mRethrowOnce = aRethrowOnce;
		}
			
		private function forwardEvent(aEvent : flash.events.Event) : void
		{
			mContext.dispatchEvent(aEvent);
		}
		
		public function startListening(): void
		{
			mDispatcher.addEventListener(mEvent, forwardEvent);
		}
		
		public function stopListening(): void
		{
			mDispatcher.removeEventListener(mEvent, forwardEvent);
		}
		
		public static function create(aContext : IEventDispatcher, 
			aDispatcher : IEventDispatcher, aEvent : String) : EventRethrower
		{		
			var result : EventRethrower = new EventRethrower(aContext, 
				aDispatcher, aEvent, false);					
			result.startListening();
			
			return result;
		}
		
		public static function createSingleTimeRethrower(aContext : IEventDispatcher, 
			aDispatcher : IEventDispatcher, aEvent : String) : EventRethrower
		{		
			var result : EventRethrower = new EventRethrower(aContext, 
				aDispatcher, aEvent, true);					
			result.startListening();
			
			return result;
		}
	}
}